import React, { useMemo, useRef, useState } from 'react'
import { StyledWrap, StyledPopWrap, CancelIcon, PopIcon } from './style'
import MedialAbility from './MedialAbility'
import { CheckBox, Input, InputNumber, Radio, RadioGroup, Select, Switch, Trigger } from '@kedacom/react-next'
import { useVirtualRoomStore } from '../../store'
import shallow from 'zustand/shallow'
import Alert from '@/components/Alert'
import AuthenticationCheck from '@/components/AuthenticationCheck'
import useCheckAuthentication from '@/components/AuthenticationCheck/useCheckAuthentication'
import { getRule } from '../../rules'
import { t } from 'i18next'
import { useGlobalStore } from '@/store/global'
import { checkPermission } from '@/utils'

const MtParams = () => {
	const [typeModalOpen, setTypeModalOpen] = useState(false)
	const [protocolModalOpen, setProtocolModalOpen] = useState(false)
	const SWITCH = useGlobalStore((state) => state.SWITCH)
	const {
		data,
		permission,
		_vrsServersList,
		_meetingTypeList,
		updateData,
		changeCallMode,
		changeRtc,
		changeMeetingType,
		changeEncryptionType,
	} = useVirtualRoomStore(
		(state) => ({
			data: state.data,
			permission: state.permission,
			_vrsServersList: state._vrsServersList,
			_meetingTypeList: state._meetingTypeList,
			updateData: state.updateData,
			changeCallMode: state.changeCallMode,
			changeRtc: state.changeRtc,
			changeMeetingType: state.changeMeetingType,
			changeEncryptionType: state.changeEncryptionType,
		}),
		shallow
	)

	const {
		run: checkAuthentication,
		open: isAuthenticationOpen,
		setOpen: setIsAuthenticationOpen,
		successFn,
	} = useCheckAuthentication({ onlyDialog: true })

	const isSfu = useMemo(() => {
		return data.meetingType === 2
	}, [data.meetingType])

	const isShowRtc = useMemo(() => {
		return (
			(data.meetingType === 0 && permission.tradMix !== 0) || (data.meetingType === 1 && permission.portMix !== 0)
		)
	}, [data.meetingType, permission])

	/**当传统会议勾选h265和4K60后，原资源预占相关按钮置灰不可修改 */
	const isSourceUsedDisabled = useMemo(
		() => data.meetingType === 0 && data.frame === 60 && data.resolution === 16,
		[data.meetingType, data.frame, data.resolution]
	)
	const encryptionTypeSourceList = useMemo(() => {
		if (data.meetingType === 2) {
			return [checkPermission('10', SWITCH.create.encryptionType) && { label: t('AES加密'), value: 2 }].filter(
				Boolean
			) as { label: string; value: number }[]
		} else {
			return [
				{ label: t('不加密'), value: 0 },
				checkPermission('10', SWITCH.create.encryptionType) && { label: t('AES加密'), value: 2 },
				!data.enableRtc &&
					permission.certificate &&
					checkPermission('01', SWITCH.create.encryptionType) && { label: t('国密加密'), value: 3 },
			].filter(Boolean) as { label: string; value: number }[]
		}
	}, [data.meetingType, data.enableRtc, permission.certificate])

	const meetingTypePanel = (
		<StyledPopWrap>
			<div className="pop-title">
				{t('会议类型注释')}
				<CancelIcon
					onClick={() => {
						setTypeModalOpen(false)
					}}
				/>
			</div>
			<div className="pop-content">
				{_meetingTypeList.find((item) => item.value === 0) && (
					<>
						<strong>{t('传统会议')}</strong>
						<div className="pop-paragraph">
							{permission.tradMix !== 0
								? t(
										'支持RTC、SIP、H.323协议的会议终端接入、电话接入；多路音视频格式可适配；具备轻量超元RTC会议的优点。'
								  )
								: t('支持SIP、H.323协议的会议终端接入、电话接入；多路音视频格式可适配。')}
						</div>
					</>
				)}
				{_meetingTypeList.find((item) => item.value === 1) && (
					<>
						<strong>{t('端口会议')}</strong>
						<div className="pop-paragraph">
							{permission.portMix !== 0
								? t(
										'支持RTC、SIP、H.323协议的会议终端接入、电话接入；为每个与会终端单独分配适配资源，实现任意视频格式、不同带宽的终端接入，获得更高质量视频体验；兼具全编全解端口会议和轻量超元RTC会议的优点。'
								  )
								: t(
										'支持SIP、H.323协议的会议终端接入、电话接入；为每个与会终端单独分配适配资源，实现任意视频格式、不同带宽的终端接入，获得更高质量视频体验。'
								  )}
						</div>
					</>
				)}
				{_meetingTypeList.find((item) => item.value === 2) && (
					<>
						<strong>{t('超元RTC会议')}</strong>
						<div className="pop-paragraph">
							{t(
								'支持RTC协议的会议终端接入；MCU转发多路视频流，与会终端可自主进行多画面的布局，资源占用小、会议容量大、网络延迟低，极致视频会议体验。'
							)}
						</div>
					</>
				)}
			</div>
		</StyledPopWrap>
	)

	const protocolPanel = (
		<StyledPopWrap>
			<div className="pop-title">
				{t('优选呼叫协议注释')}
				<CancelIcon onClick={() => setProtocolModalOpen(false)} />
			</div>
			<div className="pop-content">
				<p>{t('优选RTC时，呼叫顺序为')}RTC→SIP→H.323</p>
				<p>{t('优选SIP时，呼叫顺序为')}SIP→RTC→H.323</p>
				<p>{t('优选H.323时，呼叫顺序为')}H.323→RTC→SIP</p>
			</div>
		</StyledPopWrap>
	)

	const ref = useRef(null)
	return (
		<StyledWrap className="container" ref={ref}>
			<div className="line-wrap type-line">
				<div className="label">
					{t('会议类型')}
					<Trigger
						container={() => ref.current}
						popup={meetingTypePanel}
						popupPlacement="bottomStart"
						open={typeModalOpen}
						onClick={() => setTypeModalOpen(!typeModalOpen)}
					>
						<PopIcon className={`pop_icon ${typeModalOpen ? 'active' : ''}`} />
					</Trigger>
				</div>
				{_meetingTypeList.length > 1 ? (
					<RadioGroup
						className="row-radio"
						options={_meetingTypeList.map((item) => ({ ...item, width: 122 }))}
						value={data.meetingType}
						onChange={(e, v) => changeMeetingType(v)}
					/>
				) : (
					<div className="type-text">{_meetingTypeList[0].label}</div>
				)}
			</div>
			{isShowRtc && (
				<div className="line-wrap">
					<div className="label">{t('允许RTC接入')}</div>
					<Switch
						width={40}
						height={22}
						checked={Boolean(data.enableRtc)}
						onChange={(e, v) => {
							changeRtc(v ? 1 : 0)
						}}
					/>
				</div>
			)}
			{!isSfu && (
				<div className="line-wrap">
					<div className="label">
						{t('优先呼叫协议')}
						<Trigger
							container={() => ref.current}
							popup={protocolPanel}
							popupPlacement="bottomStart"
							open={protocolModalOpen}
							onClick={() => setProtocolModalOpen(!protocolModalOpen)}
						>
							<PopIcon className={`pop_icon ${protocolModalOpen ? 'active' : ''}`} />
						</Trigger>
					</div>
					<Select
						width={200}
						container={() => ref.current}
						options={
							data.enableRtc && !data._H265 && data.encryptionType !== 3
								? [
										{ label: 'H323', value: 0 },
										{ label: 'SIP', value: 1 },
										{ label: 'RTC', value: 2 },
								  ]
								: [
										{ label: 'H323', value: 0 },
										{ label: 'SIP', value: 1 },
								  ]
						}
						value={data.meetingProtocol}
						onChange={(e, v) => {
							updateData({ meetingProtocol: v })
						}}
					/>
				</div>
			)}
			{data.meetingType === 0 && permission.integrated && (
				<div className="line-wrap source-media-line">
					<div className="label">{t('媒体资源')}</div>
					<RadioGroup
						direction="column"
						value={data.sourceUsed}
						disabled={isSourceUsedDisabled}
						onChange={(e, v) => {
							if (v === 2) {
								if (data.enableRtc && permission.tradMix !== 0) {
									Alert(t('传统会议纯转发会议不支持RTC接入'))
									return
								}
							}
							updateData({ sourceUsed: v })
						}}
					>
						<Radio value={2} className="first-radio-item">
							{t('纯转发会议')}
							<span className="tip">{t('不占用媒体资源')}</span>
						</Radio>
						<Radio value={1}>
							{t('资源预占')}
							<span className="tip last">{t('会议始终占用媒体资源直至会议结束')}</span>
						</Radio>
					</RadioGroup>
				</div>
			)}
			<MedialAbility containerRef={ref} />
			{!isSfu && (
				<div className="line-wrap cascade-line">
					<div className="label">{t('级联会议')}</div>
					<RadioGroup
						value={data.simpleCascade}
						direction="column"
						options={[
							{ label: t('简单级联'), value: 0, className: 'first-radio-item' },
							{ label: t('合并级联'), value: 1 },
						]}
						onChange={(e, v) => {
							updateData({ simpleCascade: v })
						}}
					/>
					<div className="other-options">
						<CheckBox
							width={63}
							disabled={data.simpleCascade === 0}
							checked={data.cascadeUpload}
							onChange={(e, v) => {
								updateData({ cascadeUpload: v })
							}}
						>
							{t('上传')}
						</CheckBox>
						<CheckBox
							className="multi-uploading-checkbox__i18n"
							width={63}
							disabled={data.simpleCascade === 0}
							checked={data.cascadeReturn}
							onChange={(e, v) => {
								updateData({ cascadeReturn: v, cascadeReturnPara: '' })
							}}
						>
							{t('回传')}
						</CheckBox>
						{data.cascadeReturn && (
							<>
								<span className={`text ${data.simpleCascade === 0 ? 'disabled' : ''}`}>
									{t('带宽')}
								</span>
								<InputNumber
									className="cascade-input"
									placeholder={t('请输入')}
									focusMsg={t('回传带宽范围为：1M~1000M')}
									width={40}
									disabled={data.simpleCascade === 0}
									rule={getRule('cascadeReturnPara')}
									value={data.cascadeReturnPara}
									onChange={(e, v) => {
										updateData({ cascadeReturnPara: v })
									}}
								/>
								<span className={`text ${data.simpleCascade === 0 ? 'disabled' : ''}`}>Mbps</span>
								<CheckBox
									disabled={data.simpleCascade === 0}
									className="multi-checkbox"
									checked={data.multiStream}
									onChange={(e, v) => {
										updateData({ multiStream: v })
									}}
								>
									{t('多流')}
								</CheckBox>
							</>
						)}
					</div>
				</div>
			)}
			<div className="line-wrap">
				<div className="label">{t('初始哑音')}</div>
				<Switch
					width={40}
					height={22}
					checked={data.initMute}
					onChange={(e, v) => {
						updateData({ initMute: v })
					}}
				/>
			</div>
			<div className="line-wrap mute-exc-line">
				<div className="label">{t('全场哑音例外')}</div>
				<Switch
					width={40}
					height={22}
					checked={data.muteException}
					onChange={(e, v) => {
						updateData({ muteException: v })
					}}
				/>
				<div className="tip">{t('开启后，全场哑音操作对发言方及管理方不生效')}</div>
			</div>
			{!isSfu && (
				<div className="line-wrap auto-vmp-line">
					<div className="label">{t('自动画面合成')}</div>
					<Switch
						width={40}
						height={22}
						checked={Boolean(data.autoImageComposition)}
						onChange={(e, v) => {
							updateData({ autoImageComposition: v ? 1 : 0, nMinusOneMode: 0 })
						}}
					/>
					{data.autoImageComposition === 1 && data.meetingType === 1 && (
						<div className="n-mode">
							<span className="text">{t('N-1模式')}</span>
							<Switch
								width={40}
								height={22}
								checked={Boolean(data.nMinusOneMode)}
								onChange={(e, v) => {
									updateData({ nMinusOneMode: v ? 1 : 0 })
								}}
							/>
						</div>
					)}
				</div>
			)}
			{!isSfu && (
				<div className="line-wrap">
					<div className="label">{t('智能混音')}</div>
					<Switch
						width={40}
						height={22}
						checked={data.intelligentRemix}
						onChange={(e, v) => {
							updateData({ intelligentRemix: v })
						}}
					/>
				</div>
			)}
			{_vrsServersList.length > 1 &&
				!(data.encryptionType !== 3 && data.encryptedSM) &&
				(permission.enableLive || permission.enableVideo) &&
				permission.enableVRS && (
					<div className="line-wrap">
						<div className="label">{t('录播服务器')}</div>
						<Select
							width={200}
							container={() => ref.current}
							placeholder={t('请选择')}
							options={_vrsServersList}
							value={data.vrsId}
							onChange={(e, v) => {
								updateData({ vrsId: v })
							}}
						/>
					</div>
				)}
			{!(data.encryptionType !== 3 && data.encryptedSM) && permission.enableVideo && permission.enableVRS && (
				<div className="line-wrap video-line">
					<div className="label">{t('会议录像')}</div>
					<Switch
						width={40}
						height={22}
						checked={data.enableVideo}
						onChange={(e, v) => {
							updateData({ enableVideo: v })
						}}
					/>
					<div className="other-options">
						<CheckBox
							width={120}
							disabled={!data.enableVideo}
							checked={Boolean(data.videoPublish)}
							onChange={(e, v) => {
								updateData({ videoPublish: v ? 1 : 0 })
							}}
						>
							{t('发布到视频点播')}
						</CheckBox>
						<CheckBox
							disabled={!data.enableVideo}
							checked={Boolean(data.videoDoubleflow)}
							onChange={(e, v) => {
								updateData({ videoDoubleflow: v ? 1 : 0 })
							}}
						>
							{t('内容共享录像')}
						</CheckBox>
					</div>
				</div>
			)}
			{!(data.encryptionType !== 3 && data.encryptedSM) && permission.enableLive && permission.enableVRS && (
				<div className="line-wrap live-line">
					<div className="label">{t('会议直播')}</div>
					<Switch
						width={40}
						height={22}
						checked={data.enableLive}
						onChange={(e, v) => {
							updateData({ enableLive: v, livePassword: '' })
						}}
					/>
					<CheckBox
						className="no-login"
						disabled={!data.enableLive}
						checked={data.liveNoLogin}
						onChange={(e, v) => {
							updateData({ liveNoLogin: v })
						}}
					>
						{t('免登陆观看直播')}
					</CheckBox>
				</div>
			)}
			{data.enableLive && (
				<div className="line-wrap live-password-line">
					<div className="label">{t('直播密码')}</div>
					<Input
						width={210}
						placeholder={t('请设定密码')}
						focusMsg={t('输入6个字符，支持大小写字母和数字')}
						maxLength={6}
						rule={getRule('livePassword')}
						value={data.livePassword}
						onChange={(e, v) => {
							updateData({ livePassword: v })
						}}
					/>
				</div>
			)}
			<div className="line-wrap">
				<div className="label">{t('视频会议水印')}</div>
				<Switch
					width={40}
					height={22}
					checked={data.watermark}
					onChange={(e, v) => {
						updateData({ watermark: v })
					}}
				/>
			</div>
			{data.meetingType === 0 && !permission.integrated && (
				<div className="line-wrap source-used-line">
					<div className="label">{t('纯转发会议')}</div>
					<Switch
						width={40}
						height={22}
						disabled={isSourceUsedDisabled}
						checked={data.sourceUsed === 2}
						onChange={(e, v) => {
							if (
								v &&
								data.enableRtc &&
								data.meetingType === 0 &&
								permission.tradMix !== 0 &&
								!permission.integrated
							) {
								Alert(t('传统会议纯转发会议不支持RTC接入'))
								return
							}
							updateData({ sourceUsed: v ? 2 : 0 })
						}}
					/>
					<div className="tip">{t('开启后，仅支持召开传统纯转发类型的会议。')}</div>
				</div>
			)}
			{data.meetingType === 0 && !permission.integrated && data.sourceUsed !== 2 && (
				<div className="line-wrap source-used-line">
					<div className="label">{t('资源预占')}</div>
					<Switch
						width={40}
						height={22}
						checked={Boolean(data.sourceUsed)}
						onChange={(e, v) => {
							updateData({ sourceUsed: v ? 1 : 0 })
						}}
					/>
					<div className="tip">{t('开启后，会议始终占用资源直至会议结束')}</div>
				</div>
			)}
			{(data.enableRtc || (!data.enableRtc && data.meetingType === 2)) && !data._H265 && (
				<div className="line-wrap allow-anonymous-line">
					<div className="label">{t('匿名用户登录')}</div>
					<CheckBox
						className="allow-checkbox"
						checked={Boolean(data.allowAnonymousMt)}
						onChange={(e, v) => {
							updateData({ allowAnonymousMt: v ? 1 : 0 })
						}}
					>
						{t('允许')}
					</CheckBox>
				</div>
			)}
			{!isSfu && (
				<div className="line-wrap encryption-line">
					<div className="label">{t('传输加密')}</div>
					<Select
						container={() => ref.current}
						value={data.encryptionType}
						options={encryptionTypeSourceList}
						onChange={(e, v) => {
							changeEncryptionType(v)
						}}
					/>
					{data.encryptionType === 2 && (
						<Input
							width={210}
							placeholder={t('可输入数据加密密码')}
							focusMsg={t('可输入16个字符，包括英文字母(大小写)、数字、"."、"_"')}
							maxLength={16}
							style={{ marginLeft: 50 }}
							rule={getRule('encryptedKey')}
							value={data.encryptedKey}
							onChange={(e, v) => {
								updateData({ encryptedKey: v })
							}}
						/>
					)}
					{data.encryptionType === 3 && permission.enableQuantum && (
						<CheckBox
							style={{ marginLeft: 30 }}
							checked={Boolean(data.quantumEncryption)}
							onChange={(e, v) => {
								updateData({ quantumEncryption: v ? 1 : 0 })
							}}
						>
							{t('量通加密')}
						</CheckBox>
					)}
					{data.encryptionType === 3 && (
						<div className="certificate-options">
							{permission.sm1 && (
								<CheckBox
									width={295}
									checked={data.encryptedSM}
									onChange={(e, v) => {
										updateData({ encryptedSM: v })
									}}
								>
									{t('只允许硬件终端加入国密会议(使用SM1算法)')}
								</CheckBox>
							)}
							<CheckBox
								checked={data.encryptedAuth}
								onChange={(e, v) => {
									if (v && !permission.hasAuthenticationServer) {
										Alert(t('尚未配置动态口令服务器，不可勾选“启用终端强认证”'))
										return
									}
									//编辑状态取消勾选强认证
									if (data.vmrMoid && !v) {
										checkAuthentication(data.vmrMoid, (flag) => {
											if (flag) {
												updateData({ encryptedAuth: v })
											}
										})
									} else {
										updateData({ encryptedAuth: v })
									}
								}}
							>
								{t('启用终端强认证')}
							</CheckBox>
						</div>
					)}
				</div>
			)}

			<div className="line-wrap">
				<div className="label">{t('内容共享')}</div>
				<RadioGroup
					direction="column"
					value={data.doubleFlowLimit}
					options={[
						{ label: t('发言会场'), value: 0, className: 'first-radio-item' },
						{ label: t('任意会场'), value: 1 },
					]}
					onChange={(e, v) => {
						updateData({ doubleFlowLimit: v })
					}}
				/>
			</div>
			{!isSfu && permission.enableDCS && (
				<div className="line-wrap">
					<div className="label">{t('数据协作')}</div>
					<Switch
						width={40}
						height={22}
						checked={data.enableDCS}
						onChange={(e, v) => {
							updateData({ enableDCS: v })
						}}
					/>
					{data.enableDCS && (
						<RadioGroup
							style={{ marginLeft: 40 }}
							className="row-radio"
							value={data.dcsMode}
							options={[
								{ label: t('自由协作'), value: 2, width: 122 },
								{ label: t('管理方控制'), value: 1, width: 122 },
							]}
							onChange={(e, v) => {
								updateData({ dcsMode: v })
							}}
						/>
					)}
				</div>
			)}
			{!isSfu && (
				<div className="line-wrap">
					<div className="label">{t('视频质量')}</div>
					<RadioGroup
						className="row-radio"
						value={data.videoQuality}
						options={[
							{ label: t('质量优先'), value: 0, width: 122 },
							{ label: t('速度优先'), value: 1, width: 122 },
						]}
						onChange={(e, v) => {
							updateData({ videoQuality: v })
						}}
					/>
				</div>
			)}
			{!isSfu && (
				<div className="line-wrap">
					<div className="label">{t('呼叫方式')}</div>
					<RadioGroup
						direction="column"
						value={data.callMode}
						options={[
							{ label: t('自动呼叫'), value: 2, className: 'first-radio-item' },
							{ label: t('手动呼叫'), value: 0 },
						]}
						onChange={(e, v) => {
							changeCallMode(v)
						}}
					></RadioGroup>
					<div className="auto-call-options">
						<span>{t('呼叫间隔')}</span>
						<InputNumber
							className="call-input"
							disabled={data.callMode === 0}
							focusMsg={t('呼叫间隔为10~300秒')}
							width={45}
							maxLength={16}
							rule={getRule('callInterval')}
							value={data.callInterval}
							onChange={(e, v) => {
								updateData({ callInterval: v })
							}}
						/>
						<span style={{ color: data.callMode === 0 ? '#b6b6b6' : '#4e4e4e' }}>{t('10-300秒')}</span>
						<span style={{ marginLeft: 7, color: data.callMode === 0 ? '#b6b6b6' : '#4e4e4e' }}>
							{t('呼叫次数')}
						</span>
						<InputNumber
							className="call-input"
							disabled={data.callMode === 0 || data.callTimesUnlimited}
							focusMsg={t('呼叫次数为2~99秒')}
							width={45}
							maxLength={16}
							rule={getRule('callTimes')}
							value={data.callTimes}
							onChange={(e, v) => {
								updateData({ callTimes: v })
							}}
						/>
						<span style={{ color: data.callMode === 0 || data.callTimesUnlimited ? '#b6b6b6' : '#4e4e4e' }}>
							{t('2-99次')}
						</span>
						<CheckBox
							style={{ marginLeft: 30 }}
							checked={data.callTimesUnlimited}
							disabled={data.callMode === 0}
							onChange={(e, v) => {
								updateData({ callTimesUnlimited: v, callTimes: '' })
							}}
						>
							{t('不限次数')}
						</CheckBox>
					</div>
				</div>
			)}
			{!isSfu && (
				<div className="line-wrap">
					<div className="label">{t('语言激励')}</div>
					<Switch
						width={40}
						height={22}
						checked={data.voiceInspireEnable}
						onChange={(e, v) => {
							updateData({ voiceInspireEnable: v, voiceInspireTime: 3 })
						}}
					/>
					{data.voiceInspireEnable && (
						<Select
							container={() => ref.current}
							className="voice-inspire-time"
							value={data.voiceInspireTime}
							options={[
								{ label: '3s', value: 3 },
								{ label: '5s', value: 5 },
								{ label: '15s', value: 15 },
								{ label: '30s', value: 30 },
							]}
							onChange={(e, v) => {
								updateData({ voiceInspireTime: v })
							}}
						/>
					)}
				</div>
			)}
			<div className="line-wrap">
				<div className="label">{t('来宾会议室')}</div>
				<Switch
					width={40}
					height={22}
					checked={data.publicMeeting}
					onChange={(e, v) => {
						updateData({ publicMeeting: v })
					}}
				/>
			</div>
			{!isSfu && (
				<div className="line-wrap">
					<div className="label">{t('归一重整')}</div>
					<Switch
						width={40}
						height={22}
						checked={data.oneReforming}
						onChange={(e, v) => {
							updateData({ oneReforming: v })
						}}
					/>
				</div>
			)}
			{!isSfu && (
				<div className="line-wrap">
					<div className="label">FEC</div>
					<Switch
						width={40}
						height={22}
						checked={Boolean(data.fecMode)}
						onChange={(e, v) => {
							updateData({ fecMode: v ? 1 : 0 })
						}}
					/>
				</div>
			)}
			<AuthenticationCheck open={isAuthenticationOpen} setOpen={setIsAuthenticationOpen} callBack={successFn} />
		</StyledWrap>
	)
}

export default MtParams
